package com.study.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.dto.LoginFormDTO;
import com.study.dto.Result;
import com.study.dto.UserDTO;
import com.study.entity.User;
import com.study.mapper.UserMapper;
import com.study.service.IUserService;
import com.study.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.study.utils.RedisConstants.*;
import static com.study.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCodoe(String phone, HttpSession session) {
        //判断手机号码格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            //手机号码无效，返回错误信息
            return Result.fail("手机号码格式错误!");
        }
        //生成验证码
        String code = RandomUtil.randomString(6);
        log.debug("验证码信息：{}", code);
        //将code信息保存到Redis并设置超期时间
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //判断手机号码
        if (phone == null || RegexUtils.isPhoneInvalid(phone)) {
            //手机号码无效，返回错误信息
            return Result.fail("手机号码格式错误!");
        }
        // 从Redis中获取Redis并判断
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !code.equals(cacheCode)) {
            return Result.fail("用户没有请求过验证码");
        }
        //查询数据库中的用户信息
        User user = query().eq("phone", phone).one();
        //如果用户信息为空则创建
        if (user == null) {
            user = createUserByPhone(phone);
        }

        // 生成随机token
        String token = UUID.fastUUID().toString(true);

        //  将userDto转换成Map
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, filedValue) -> filedValue.toString()));

        // 将用户信息保存到Redis并设置超期时间
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY + token,LOGIN_USER_TTL,TimeUnit.MINUTES);

        //登录成功，删除Redis中的验证码
        stringRedisTemplate.delete(LOGIN_CODE_KEY + phone);

        //返回token
        return Result.ok(token);
    }

    private User createUserByPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(8));
        save(user);
        return user;
    }
}
